package dbUtil

import (
	"context"
	"errors"
	"github.com/go-sql-driver/mysql"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/util/gconv"
)

// 截断表
func TruncateTable(ctx context.Context, dbConnGroup, table string) (err error) {
	sql := "truncate table  " + table
	db := g.DB(dbConnGroup)
	_, err = db.Query(ctx, sql)
	return
}

// 释放空间
func OptimizeTable(ctx context.Context, dbConnGroup, table string) (err error) {
	sql := "OPTIMIZE table  " + table
	db := g.DB(dbConnGroup)
	_, err = db.Query(ctx, sql)
	return
}

// 获取该数据库使用空间
func GetThisDbUsedSize(ctx context.Context, dbConnGroup string) (size float64, err error) {
	table_schema := "gfast" + dbConnGroup
	sql := "select table_schema as 'dbSchema',sum(table_rows) AS 'row_count'," +
		"ROUND(SUM(data_length + index_length) / 1024 / 1024 , 3) AS 'size' " +
		"from information_schema.tables where table_schema='" + table_schema + "'"
	db := g.DB(dbConnGroup)
	allResult, err := db.Query(ctx, sql)
	if err != nil {
		return 0, err
	}
	all := allResult.List()
	length := allResult.Len()
	if length > 0 {
		size = gconv.Float64(all[0]["size"]) //MB 3位小数
	}
	return
}

// 获取该数据库的该表使用空间
func GetThisTableUsedSize(ctx context.Context, dbConnGroup string, table string) (size float64, err error) {
	table_schema := "gfast" + dbConnGroup
	sql := "SELECT " +
		" table_name AS `table_name`," +
		" round(((data_length + index_length) / 1024 / 1024 ), 3) AS `size`" +
		" FROM information_schema.tables WHERE table_schema = '" + table_schema + "' " +
		" AND table_name = '" + table + "';"
	db := g.DB(dbConnGroup)
	allResult, err := db.Query(ctx, sql)
	if err != nil {
		return 0, err
	}
	all := allResult.List()
	length := allResult.Len()
	if length > 0 {
		size = gconv.Float64(all[0]["size"]) //MB 3位小数
	}
	return
}

func IsTableNotExistError(err error) bool {
	if err == nil {
		return false
	}
	// 类型断言获取 MySQL 错误信息
	var mysqlErr *mysql.MySQLError
	if errors.As(err, &mysqlErr) {
		// 错误代码 1146 是 "Table doesn't exist" 错误
		if mysqlErr.Number == 1146 {
			return true
		}
	}
	return false
}
